package com.fjp.heartguard.ui.question

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.fjp.heartguard.R
import com.fjp.heartguard.app.Constants
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.data.bean.OlderInfo
import com.fjp.heartguard.app.eventViewModel
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.databinding.ActivityRecordBinding
import com.fjp.heartguard.viewmodel.RecordViewModel
import com.zlw.main.recorderlib.RecordManager


class RecordActivity : BaseActivity<RecordViewModel, ActivityRecordBinding>() {
    val REQUEST_RECORD_AUDIO_PERMISSION = 200
    var olderInfo: OlderInfo? = null
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.click = ClickProxy()
        mViewModel.title.set(getString(R.string.question_title))
        olderInfo = intent.getParcelableExtra<OlderInfo>(Constants.Intent_REPORT)
    }

    override fun createObserver() {
        super.createObserver()
        eventViewModel.saveQuestionSuccess.observeInActivity(this) {
            finish()
        }
    }

    inner class ClickProxy {
        fun clickSure() {
            if (ContextCompat.checkSelfPermission(this@RecordActivity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this@RecordActivity, arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_RECORD_AUDIO_PERMISSION);
            } else {
                QuestionActivity.hasVoice=true
                RecordManager.getInstance().start()
                startQuestionActivity()
            }
        }

        fun clickNo() {
            QuestionActivity.hasVoice=false
            startQuestionActivity()
        }
    }

    fun startQuestionActivity() {
        val intent = Intent(this@RecordActivity, QuestionActivity::class.java)
        if (olderInfo != null) {
            intent.putExtra(Constants.Intent_REPORT, olderInfo)
        }
        startActivity(intent)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            if (ContextCompat.checkSelfPermission(this@RecordActivity, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以继续录音操作
                RecordManager.getInstance().start()
                startQuestionActivity()
            } else {
                // 权限被拒绝，处理权限拒绝的情况
                showToast("权限被拒绝无法录音")
            }
        }
    }

}